<?php
class Controller_Login extends FLEA_Controller_Action {
     function actionindex() {
        $smarty =& $this->_getView();
        $smarty->display('login.html');
     }
    function actionlogout() {
        session_destroy();
        js_alert('您已经退出！','',url('Default'));        
    }
	function actionlogin() {
        $row = array(
		'username' => strip_tags($_POST['username']),
		'password' => strip_tags($_POST['password']),
		);
	    $usersManager =& FLEA::getSingleton('Model_users');
	    $user = $usersManager->findByUsername($row['username']);
	    if (!$user || !$usersManager->checkPassword($row['password'], $user[$usersManager->passwordField])) {
            echo "Username invalid or password mismatch.";
            exit;
	    }
	    $roles = $usersManager->fetchRoles($user);
	    $rbac =& FLEA::getSingleton('FLEA_Com_RBAC');
	    $sessionUser = array(
            'USERID' => $user[$usersManager->primaryKey],
            'USERNAME' => $user[$usersManager->usernameField],
	    );
        // $_SESSION["userid"] = $user[$usersManager->primaryKey];
        // $_SESSION["username"] = $user[$usersManager->usernameField];
	    $rbac->setUser($sessionUser, $roles);

        $roles = $rbac->getRoles();
	    $roles = is_array($roles)?$roles:array();
        if(in_array('user', $roles)) {
            redirect(url());
        }
        elseif(in_array('admin',$roles)) {
            redirect(url('edit'));
        }
        elseif(in_array('root',$roles)) {
            redirect(url('edit'));
        }
        else {
            js_alert('登录成功, 权限不够，请联系管理员','',$this->_forward());
        }
    }
    function _goBack() {
        $url = $this->_getBack();
        unset($_SESSION['BACKURL']);
        redirect($url);
    }

    /**
     * 设置返回点 URL，稍后可以用 _goBack() 返回
     */
    function _setBack() {
        $_SESSION['BACKURL'] = encode_url_args($_GET);
    }

    /**
     * 获取返回点 URL
     *
     * @return string
     */
    function _getBack() {
        if (isset($_SESSION['BACKURL'])) {
            $url = $this->rawurl($_SESSION['BACKURL']);
        } else {
            $url = $this->_url();
        }
        return $url;
    }
}
